package com.zxw.springtest.user.service;

import javax.security.auth.login.AccountNotFoundException;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.zxw.springtest.login.domin.LoginVO;
import com.zxw.springtest.login.service.LoginService;

/**
 * 类描述		重写realm,realm中验证用户登录用户名和密码，并进行权限分配
 * @author zhengxw
 * @since 2016年12月30日
 */
public class MyShiroRealm extends AuthorizingRealm{
	@Autowired
	private LoginService loginService;
	
	Logger logger = LoggerFactory.getLogger(MyShiroRealm.class);

	/**
	 * 方法描述	登陆信息和用户验证信息验证
	 * @author zhengxw
	 * @since 2017年1月4日
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) 
			throws AuthenticationException {		
		//获取用户名
		UsernamePasswordToken userToken = (UsernamePasswordToken)token;
		String userName = userToken.getUsername();
		String passWord	= String.valueOf(userToken.getPassword());
		//通过用户名获取用户详细信息（对比密码是否正确）
		LoginVO vo = null;
		try{
			vo = loginService.getUserInfoByUsername(userName);
		}catch (Exception e) {
			e.printStackTrace();
			throw new AccountException("未知系统异常！");
		}
		if (vo == null) {
			logger.debug("获取认证信息：登录用户【{}】不存在", userName);
			throw new UnknownAccountException("用户信息不存在！");
	    }
	    if (!vo.getPASSWORD().equals(passWord)) {
	        logger.debug("获取认证信息：登录用户【{}】密码错误", userName);
	        throw new IncorrectCredentialsException("用户名/密码错误！");
	    }		
		
		return new SimpleAuthenticationInfo(userName, userToken.getPassword(), getName());
	}
		
	
	/**
	 * 方法描述	获取角色权限
	 * 	授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法(non-Javadoc)
	 * @author zhengxw
	 * @since 2017年1月11日
	 * @param principals
	 * @return
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		return null;		
	}
	
	@Override
	public String getName() {
		return getClass().getName();
	}
}
